﻿using System.Threading.Tasks;
using FDSimpleModelGenerator.Common;
using FDSimpleModelGenerator.Common.Mvc;
using FDSimpleModelGenerator.Common.Mvc.Filters;
using FDSimpleModelGenerator.Common.Mvc.PageModels;
using FDSimpleModelGenerator.IServices;
using FDSimpleModelGenerator.Models;
using Microsoft.AspNetCore.Mvc;

namespace FDSimpleModelGenerator.Pages
{
    public class LoginModel : LoginBaseModel
    {
        private readonly ISysUserService _sysUserService;

        public LoginModel(ISysUserService sysUserService)
        {
            _sysUserService = sysUserService;
        }

        public async Task<IActionResult> OnGetAsync()
        {
            await Task.CompletedTask;
            //if (User.Identity.IsAuthenticated)
            //{
            //    return Redirect("/");
            //}

            return Page();
        }

        public async Task<IActionResult> OnPostAsync(LoginParamModel model)
        {
            var isSuccess = false;
            if (_sysUserService.IsValidLogin(model.UserName.Trim(), model.Password.Trim().ToEncryptString(), out int userId))//(model.UserName == "admin" && model.Password == "abc123")
            {
                isSuccess = true;
                await UserContext.Current.LoginAsync(model.UserName, userId);
            }
            if (Request.ContentType == "application/json")
            {
                return new JsonResult(new { Code = isSuccess ? 0 : 400, Message = isSuccess ? "登录成功" : "失败" });
            }

            if (!isSuccess)
            {
                ModelState.AddModelError("", "用户名或密码错误");
                return Page();
            }
            string returnUrl = Request.Query["ReturnUrl"];
            returnUrl = returnUrl.IsNullOrEmpty() ? "/" : returnUrl;

            return Redirect(returnUrl);
        }

        public async Task<IActionResult> OnGetLogoutAsync()
        {
            await UserContext.Current.LogoutAsyn();
            return Redirect("/Login");
        }
    }
}